package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import freemarker.template.Configuration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {

    @Autowired
    private Configuration configuration;

    @Resource(name = "minIOFileStorageService")
    private FileStorageService fileStorageService;

    @Autowired
    private AuthorMapper authorMapper;

    @Value("${file.minio.prefix}")
    private String prefix;

    @Autowired
    ApArticleMapper apArticleMapper;

    /**
     * 生成文章静态页面
     */
    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {
        try {
            // 指定模板
            Template opm = configuration.getTemplate("article.ftl");
            if (opm==null){
                CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"获取模板失败");
            }
            // 数据
            Map<String, Object> params = new HashMap<>();
            // 文章详情
            params.put("content", JSON.parseArray(content));
            // 文章信息
            params.put("article",apArticle);
            // 作者 对应的 apUserId
            ApAuthor author = authorMapper.selectById(apArticle.getAuthorId());
            params.put("authorApUserId", author.getUserId());
            if (author==null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"作者信息不存在");
            }
            StringWriter out = new StringWriter();
            // 生成html文件上传到minio中
            opm.process(params,out);
            ByteArrayInputStream is = new ByteArrayInputStream(out.toString().getBytes());
            // 生成页面把html文件上传到minio中
            String path = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", is);
            // 修改ap_article表，保存static_url字段
            apArticle.setStaticUrl(path);
            apArticleMapper.updateById(apArticle);
            log.info("文章详情静态页生成成功 staticUrl=====> {}", path);
        } catch (IOException e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"报错信息为"+e.getMessage());
        } catch (TemplateException e) {
            e.printStackTrace();CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"原因: 替换模板失败报错信息为 "+e.getMessage());
        }

    }
}
